package com.crocodileQ.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crocodileQ.common.AppException;
import com.crocodileQ.common.R;
import com.crocodileQ.constants.SystemConstants;
import com.crocodileQ.domain.VO.BlogUserLoginVO;
import com.crocodileQ.domain.VO.UserInfoVO;
import com.crocodileQ.domain.entity.LoginUser;
import com.crocodileQ.domain.entity.User;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.mapper.UserMapper;
import com.crocodileQ.service.BlogLoginService;
import com.crocodileQ.service.LoginService;
import com.crocodileQ.utils.BeanCopyUtil;
import com.crocodileQ.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class SystemLoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param user
     * @return
     */
    public R<HashMap> login(User user) {

//        处理非管理账号登录
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getType, SystemConstants.IS_ADMIN);
        List<User> users = userMapper.selectList(queryWrapper);
        if(users.size() < 1){
            return R.error(AppExceptionMsgEnum.LOGIN_ERROR);
        }

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (BeanUtil.isEmpty(authenticate)){
            throw new AppException(AppExceptionMsgEnum.REQUIRED_USERNAME);
        }


        //生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJwt(userId);

        //todo redis 缓存loginUser
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);


        return R.success(map);
    }

    @Override
    public R logout() {

        SecurityContextHolder.clearContext();
        return R.success("退出登录成功");
    }


}
